/*给定一个n个元素有序的（升序）整型数组nums 和一个目标值target ，写一个函数搜索nums中的 target，
* 如果目标值存在返回下标，否则返回 -1。
*
* 输入: nums = [-1,0,3,5,9,12], target = 9
* 输出: 4
* 解释: 9 出现在 nums 中并且下标为 4
* */

package newcoder.BinarySearch_4;

import java.util.Arrays;

public class Leetcode704 {

    public static void main(String[] args) {
        Leetcode704 obj = new Leetcode704();
        int[] nums = {-1,0,3,5,9,12};
        int target = 2;
        System.out.println(obj.search(nums, target));
    }

    public int search(int[] nums, int target){

        int len = nums.length;
        int left = 0;
        int right = len - 1;
        while (left <= right){
            int i = (right + left) / 2;
            if (nums[i] == target){
                return i;
            }
            if (nums[i] > target){
                right = i - 1;
            }else {
                left = i + 1;
            }
        }
        return -1;
    }
}
